const router = require('express').Router()
const pool = require('../db/pool.js')

router.post('/deliveryAddress/add', async (req, res) => {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return 
  }

  let { consignee, consignee_tel, area, address } = req.body
  let consumer_id = req.user.id
  let sql = `insert into delivery_address (consignee, consignee_tel, area, address, consumer_id) values ('${ consignee }', '${ consignee_tel }', '${ area }', '${ address }', ${consumer_id})`

  let result = await pool.query(sql)

  res.status(200).json(result[0])
})

router.delete('/deliveryAddress/del', async (req, res) => {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return 
  }

  let id = req.query.id
  let sql = `delete from delivery_address where id = ${ id }`
  let result = await pool.query(sql)

  res.status(200).json(result[0])
})

router.put('/deliveryAddress', async (req, res) => {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return
  }

  let { id, consignee, consignee_tel, area, address } = req.body
  let consumer_id = req.user.id

  let sql = `update delivery_address set consignee = '${ consignee }', consignee_tel = '${ consignee_tel }', area = '${ area }', address = '${ address }', consumer_id = ${ consumer_id } where id = ${ id }`
  let result = await pool.query(sql)

  res.status(200).json(result[0])
})

router.get('/deliveryAddress', async (req, res) => {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return 
  }

  let consumer_id = req.user.id

  let sql = `select * from delivery_address where consumer_id = ${ consumer_id }`
  let result = await pool.query(sql)

  res.status(200).json(result[0])
})

module.exports = router